package com.maple.service.impl;

import com.alibaba.druid.support.json.JSONUtils;
import com.alipay.api.AlipayApiException;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.maple.dto.*;
import com.maple.entity.*;
import com.maple.enumeration.ExceptionEnum;
import com.maple.exception.BusinessException;
import com.maple.mapper.*;
import com.maple.result.PageResult;
import com.maple.service.AddressBookService;
import com.maple.service.OrderService;
import com.maple.utils.AlipayUtils;
import com.maple.utils.ThreadLocalUtils;
import com.maple.vo.OrderStatisticsVO;
import com.maple.vo.OrderSubmitVO;
import com.maple.vo.OrderVO;
import com.maple.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.web.OffsetScrollPositionHandlerMethodArgumentResolver;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

import java.time.LocalDateTime;
import java.util.*;


@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WebSocketServer webSocketServer;
    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO sudmit(OrdersSubmitDTO ordersSubmitDTO) {
//        封装对象
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, order);

//        查询数据库中的数据
        AddressBook addressBook = new AddressBook();
        addressBook.setId(order.getAddressBookId());
        List<AddressBook> query = addressBookMapper.query(addressBook);
        User user = userMapper.queryByUserId(ThreadLocalUtils.getCurrentId());
        List<ShoppingCart> cart = shoppingCartMapper.queryByUserId(ThreadLocalUtils.getCurrentId());

        if(query == null || query.get(0) == null){
            throw new BusinessException(ExceptionEnum.ADDRESS_BOOK_IS_NULL);
        }

        if(cart == null){
            throw new BusinessException(ExceptionEnum.SHOPPING_CART_IS_NULL);
        }

//        使用支付宝的接口
        String uuid = String.valueOf(UUID.randomUUID());
        String tradeNo = "";
        try {
            tradeNo = AlipayUtils.buildOrder(uuid, order.getAmount(), order.getRemark());
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

//        完善数据
        order.setNumber(uuid);
        order.setStatus(Orders.PAID);
        order.setUserId(ThreadLocalUtils.getCurrentId());
        order.setPayStatus(Orders.UN_PAID);
        order.setAddress(query.get(0).getDetail());
        order.setPhone(query.get(0).getPhone());
        order.setConsignee(query.get(0).getConsignee());
        order.setUserName(user.getName());
        order.setOrderTime(LocalDateTime.now());
        order.setTradeNo(tradeNo);

//        数据库订单新增
        Orders orders = orderMapper.add(order);

//        数据库订单明细批量新增
        orderDetailMapper.add(cart);

//        数据库中对应用户的购物车删除操作
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(ThreadLocalUtils.getCurrentId());
        shoppingCartMapper.delete(shoppingCart);

//        返回值
        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderAmount(order.getAmount())
                .orderNumber(order.getNumber())
                .orderTime(order.getOrderTime())
                .tradeNo(order.getTradeNo())
                .build();
    }

    /**
     * 订单条件查询
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    @Transactional
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
//        数据库查询订单
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> query = orderMapper.query(ordersPageQueryDTO);

//        数据库查询订单明细数据
        List<OrderVO> list = null;
        if (query == null || query.getTotal() == 0) {
            return new PageResult();
        }

        list = getOrderVO(query);
//        返回
        return new PageResult(query.getTotal(), list);
    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @Override
    @Transactional
    public OrderVO orderDetail(String id) {
        OrderVO orderVO = new OrderVO();
        Orders orders = orderMapper.queryByOrderId(id);
        List<OrderDetail> orderDetails = orderDetailMapper.queryByOrderId(Long.valueOf(id));
        orderVO.setOrderDetailList(orderDetails);
        orderVO.setOrder(orders);
        return orderVO;
    }

    /**
     * 再来一单，根据订单id批量新增购物车数据
     * @param id
     */
    @Override
    @Transactional
    public void repetition(String id) {
//        查询订单明细数据
        List<OrderDetail> orderDetails = orderDetailMapper.queryByOrderId(Long.valueOf(id));

//        封装为购物车数据
        List<ShoppingCart> list = new ArrayList<>();
        for(OrderDetail orderDetail : orderDetails){
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setUserId(ThreadLocalUtils.getCurrentId());
            list.add(shoppingCart);
        }

//        新增数据库购物车
        shoppingCartMapper.addAll(list);
    }

    /**
     * 各个状态的订单数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO queryStatistics() {
//        封装对象
        Orders orders = new Orders();
        OrderStatisticsVO statisticsVO = new OrderStatisticsVO();
        orders.setStatus(Orders.TO_BE_CONFIRMED);
//        查询数据库
        statisticsVO.setToBeConfirmed(orderMapper.queryStatistics(orders));
        orders.setStatus(Orders.CONFIRMED);
        statisticsVO.setConfirmed(orderMapper.queryStatistics(orders));
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        statisticsVO.setDeliveryInProgress(orderMapper.queryStatistics(orders));

//        返回
        return statisticsVO;
    }

    /**
     * 接单
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
//        封装对象
        ordersConfirmDTO.setStatus(Orders.CONFIRMED);
//        数据库更新
        orderMapper.updateStatus(ordersConfirmDTO);
    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
//        查询数据库
        Orders orders1 = orderMapper.queryByOrderId(String.valueOf(ordersRejectionDTO.getId()));
        if(orders1 == null || !Objects.equals(orders1.getStatus(), Orders.TO_BE_CONFIRMED)){
            throw new BusinessException(ExceptionEnum.ORDER_STATUS_ERROR);
        }

//        封装对象
        Orders orders = Orders.builder()
                .id(ordersRejectionDTO.getId())
                .rejectionReason(ordersRejectionDTO.getRejectionReason())
                .cancelTime(LocalDateTime.now())
                .build();

//        接口调用
        try {
            AlipayUtils.rejection(orders1.getAmount(), orders1.getTradeNo(), orders1.getRejectionReason());
        } catch (AlipayApiException e) {
            throw new BusinessException(ExceptionEnum.ALIPAY_ERROR);
        }
//        数据库更新
        orderMapper.update(orders);
    }

    /**
     * 商家取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
//      封装对象
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersCancelDTO, orders);
        Orders orders1 = orderMapper.queryByOrderId(String.valueOf(ordersCancelDTO.getId()));

        if(orders1 == null){
            throw new BusinessException(ExceptionEnum.ORDER_NOT_FOUND);
        }

//        接口调用
        if (orders1.getPayStatus().equals(Orders.PAID)) {
            try {
                AlipayUtils.rejection(orders1.getAmount(), orders1.getTradeNo(), ordersCancelDTO.getCancelReason());
            } catch (AlipayApiException e) {
                throw new BusinessException(ExceptionEnum.ALIPAY_ERROR);
            }
        }

//        数据库更新
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 用户取消订单
     * @param id
     */
    @Override
    public void userCancel(String id) {
//        查询数据库
        Orders orders = orderMapper.queryByOrderId(id);

//        判断订单是否存在
        if(orders == null){
            throw new BusinessException(ExceptionEnum.ORDER_NOT_FOUND);
        }

//        判断订单状态是否为待接单以后的状态
        if(orders.getStatus() > Orders.TO_BE_CONFIRMED){
//            由商家取消订单
            throw new BusinessException(ExceptionEnum.ORDER_CONFIRMED);
        }

//        判断订单是否已经支付并未接单，进行退款操作
        if(orders.getStatus().equals(Orders.TO_BE_CONFIRMED)){
            try {
                AlipayUtils.rejection(orders.getAmount(), orders.getTradeNo(), "用户取消订单");
            } catch (AlipayApiException e) {
                throw new BusinessException(ExceptionEnum.ALIPAY_ERROR);
            }
            orders.setPayStatus(Orders.REFUND);
        }

//        判断订单是否为待付款状态
        if(orders.getStatus().equals(Orders.PENDING_PAYMENT)){
            try {
                AlipayUtils.cancelOrder(id);
            } catch (AlipayApiException e) {
                throw new BusinessException(ExceptionEnum.ALIPAY_ERROR);
            }
        }

//        更新数据库：订单状态，取消原因，取消时间
        Orders orders1 = new Orders();
        orders1.setUserId(Long.valueOf(id));
        orders1.setStatus(Orders.CANCELLED);
        orders1.setCancelReason("用户取消订单");
        orders1.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders1);

    }

    /**
     * 派送订单
     * @param id
     */
    @Override
    public void delivery(String id) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.queryByOrderId(id);

        // 校验订单是否存在，并且状态为3
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.CONFIRMED)) {
            throw new BusinessException(ExceptionEnum.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        // 更新订单状态,状态转为派送中
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);

        orderMapper.update(orders);
    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void complete(String id) {
//        查询数据库
        Orders orders1 = orderMapper.queryByOrderId(id);
        if(orders1 == null){
            throw new BusinessException(ExceptionEnum.ORDER_NOT_FOUND);
        }

        if(orders1.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)){
            throw new BusinessException(ExceptionEnum.ORDER_STATUS_ERROR);
        }

//        封装对象
        Orders orders = new Orders();
        orders.setId(Long.valueOf(id));
        orders.setStatus(Orders.COMPLETED);


//        数据库更新
        orderMapper.update(orders);
    }

    /**
     * 用户催单
     * @param id
     */
    @Override
    public void reminder(String id) {
//        查询数据库
        Orders orders1 = orderMapper.queryByOrderId(id);

//        判断是否为null
        if(orders1 == null){
            throw new BusinessException(ExceptionEnum.ORDER_NOT_FOUND);
        }

//        封装请求连接数据
        Map<Object, Object> map = new HashMap<>();
        map.put("type", 2);
        map.put("orderId", orders1.getId());
        map.put("content", "用户id：" + orders1.getUserId() + ",手机号：" + orders1.getPhone());

//        发送长连接
        String json = JSONUtils.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }


    private List<OrderVO> getOrderVO(Page<Orders> page){
        List<Orders> result = page.getResult();
        List<OrderVO> list = new ArrayList<>();

        for(Orders order : result){
            OrderVO orderVO = new OrderVO();
            orderVO.setOrder(order);
            List<OrderDetail> list1 = orderDetailMapper.queryByOrderId(order.getId());
            orderVO.setOrderDetailList(list1);
            list.add(orderVO);
        }
        return list;
    }







}
